package cn.afactory.tygz.ui.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tendcloud.tenddata.TCAgent;

import org.json.JSONObject;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.sns.Constants;
import cn.afactory.tygz.ui.MainActivity;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.LoadingDialog;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;

/**
 * Created with Android Studio.
 * Title:BaseActivity
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/8/28
 * Time:下午4:22
 * Version 1.0
 */
public class LoginActivity extends BaseActivity {
    private Context context;
    private EditText mPhoneNumberEditText;
    private IWXAPI mWXApi;
    private EditText mPasswordEt;
    private TextView mFrogetPwdTv;
    private TextView mLoginBtn;
    private TextView mBtnRegister;
    //微信登陆的按钮
    private Button mWeixinLoginBtn;
    private Button login_qq_btn;
    public static Tencent mTencent;
    private TextView tv_forget;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        initQQ();
        initWXAPI();

        setContentView(R.layout.ac_login);

        setTitleText(getString(R.string.label_title_login));
        initUI();
    }
    /****************************************QQ BEGIN************************************/
    private void initQQ(){
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, this);
        }
    }

    IUiListener mQQLoginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            LocalUtils.showToast(LoginActivity.this, R.string.toast_qq_login_success);
            initOpenidAndToken(values);
        }
    };


    private void doQQLogin(String accessToken){
        showLoadingDialog("");
//        NetManager.getInstance(this).doQqLogin(accessToken, new OnResponseListener<Boolean>() {
//
//            @Override
//            public void onInernError(int errorCode, String errorMessage) {
//                hideLoadingDialog();
//                LocalUtils.showToast(LoginActivity.this, errorMessage);
//            }
//
//            @Override
//            public void onComplete(boolean isOK, Boolean result, int errorCode,
//                                   String errorMsg) {
//                if(isOK && result){
//                    gotoMain();
//                }else{
//                    hideLoadingDialog();
//                    LocalUtils.showToast(LoginActivity.this, StringUtil.handlerErrorCode(LoginActivity.this, errorCode));
//                }
//            }
//        });
    }

    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
            doQQLogin(token);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                LocalUtils.showToast(LoginActivity.this,R.string.toast_qq_login_failed);
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                LocalUtils.showToast(LoginActivity.this,R.string.toast_qq_login_failed);
                return;
            }

            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
        }

        @Override
        public void onCancel() {
        }
    }
    /****************************************QQ END************************************
    //TODO
    /****************************************WeiBo END************************************/
    @Override
    protected void onResume() {
        String lastPhoneNumber = getLastPhoneNumber();
        if (lastPhoneNumber != null && mPhoneNumberEditText != null) {
            mPhoneNumberEditText.setText(getLastPhoneNumber());
        }

//        mPhoneNumberEditText.setText("18616312220");
//        mPasswordEt.setText("123456");

//        if(mTencent != null && mTencent.isSupportSSOLogin(this)){
//            login_qq_btn.setVisibility(View.VISIBLE);
//        }else{
//            login_qq_btn.setVisibility(View.GONE);
//        }
        login_qq_btn.setVisibility(View.GONE);

//        if(mWXApi != null && mWXApi.isWXAppInstalled()){
//            mWeixinLoginBtn.setVisibility(View.VISIBLE);
//        }else{
//            mWeixinLoginBtn.setVisibility(View.GONE);
//        }
        mWeixinLoginBtn.setVisibility(View.GONE);

        super.onResume();
        TCAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TCAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.right_in, R.anim.left_out);
    }

    private void initUI() {

        setRightButton(getString(R.string.label_btn_register), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));

            }
        });
        tv_forget = (TextView) findViewById(R.id.tv_forget);
        tv_forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ResetPwdActivity.class));

            }
        });
        mPhoneNumberEditText = (EditText) findViewById(R.id.phone_number_edit);
        mPhoneNumberEditText
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE
                                || actionId == EditorInfo.IME_ACTION_SEND
                                || actionId == EditorInfo.IME_ACTION_GO
                                || actionId == EditorInfo.IME_ACTION_SEARCH
                                || actionId == EditorInfo.IME_ACTION_NEXT
                                || actionId == EditorInfo.IME_ACTION_PREVIOUS) {
                            doLogin();
                            return true;
                        }
                        return false;
                    }
                });

        mPasswordEt = (EditText)findViewById(R.id.password_edit);
        mPasswordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_GO) {

                    doLogin();
                    return true;
                }
                return false;
            }
        });

        mFrogetPwdTv = (TextView)findViewById(R.id.tv_forget_pwd);
        mFrogetPwdTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ResetPwdActivity.class));
            }
        });


        mBtnRegister = (TextView)findViewById(R.id.tv_register);
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });

        mLoginBtn = (TextView) findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLogin();
            }
        });

        mWeixinLoginBtn = (Button) findViewById(R.id.login_weixin_btn);
        mWeixinLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLoginByWeiXin();
            }
        });

        //QQ登陆
        login_qq_btn = (Button) findViewById(R.id.login_qq_btn);
        login_qq_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLoginQQ();
            }
        });

        mPhoneNumberEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mPasswordEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        TextView tv_app_protocal = (TextView) findViewById(R.id.tv_app_protocal);
        tv_app_protocal.setText(Html
                .fromHtml(getString(R.string.label_protocal_hint_new)));
        tv_app_protocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegProtocolActivity.class));
            }
        });

        showLoginButton();
    }

    /**
     * QQ登录
     */
    private void doLoginQQ(){
        if (mTencent != null && mTencent.isSessionValid()) {
            // TODO 已经登录
//			mTencent.logout(this);
            doQQLogin(mTencent.getAccessToken());
        } else {
            // TODO 未登录
            mTencent.login(this, "all", mQQLoginListener);
        }
    }


    private void doLoginByWeiXin(){
        if(!isSupported()){
            showErrorMsg(R.string.weixin_not_installed);
//			LocalUtils.showCenterToast(LoginActivity.this, R.string.weixin_not_installed);
        }else{
            doLoginWeixin();
        }
    }

    public void initWXAPI(){
        mWXApi = WXAPIFactory.createWXAPI(context, Constants.WEIXIN_APP_ID, false);
        registerToWX();
    }

    private void registerToWX(){
        mWXApi.registerApp(Constants.WEIXIN_APP_ID);
    }

    public boolean isSupported(){
        return mWXApi.isWXAppInstalled() && mWXApi.isWXAppSupportAPI();
    }

    /**
     * 登录微信
     */
    private void doLoginWeixin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "sns_userlogin";
        mWXApi.sendReq(req);
    }

    private String getLastPhoneNumber() {
        return SPUtils.getMobilePhone(this);
    }

    private void showLoginButton(){
        if(!TextUtils.isEmpty(mPhoneNumberEditText.getText().toString())
                && !TextUtils.isEmpty(mPasswordEt.getText().toString())) {
            mLoginBtn.setClickable(true);
            mLoginBtn.setEnabled(true);
            mLoginBtn.setPressed(true);
            mLoginBtn.setBackgroundResource(R.drawable.btn_rect_orange_fill_press);
        } else {
            mLoginBtn.setClickable(false);
            mLoginBtn.setEnabled(false);
            mLoginBtn.setPressed(false);
            mLoginBtn.setBackgroundResource(R.drawable.btn_rect_orange_fill_disable);
        }
    }

    private LoadingDialog loadingDialog;
    protected void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = DialogUtil.showLoadingDialog(this, msg, true);
        }
        if (!TextUtils.isEmpty(msg)) {
            loadingDialog.setDlgMessage(msg);
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    protected void hideLoadingDialog() {
        if (!isFinishing() && loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        }
    }

    private void showErrorMsg(String msg) {
        LocalUtils.showToast(this, msg);
    }

    private void showErrorMsg(int resId) {
        LocalUtils.showToast(this, resId);
    }

    /**
     * 处理登里事件
     */
    private void doLogin() {
        String phoneNum = mPhoneNumberEditText.getText().toString().trim();
        String password = mPasswordEt.getText().toString().trim();

        if(phoneNum.length() < 1){
            LocalUtils.showToast(this,R.string.phone_number_null);
            return;
        }

        if(!LocalUtils.isMobileNO(phoneNum)){
            LocalUtils.showToast(this,R.string.label_invalid_phonenumber);
            return;
        }

        if(password.length() < 1){
            LocalUtils.showToast(this,"请输入密码");
            return;
        }

        showLoadingDialog(getString(R.string.dlg_msg_logining));
        NetManager.getInstance(context).doLogin(phoneNum, password, new OnResponseListener<UserInfo>() {
            @Override
            public void onComplete(boolean isOK, UserInfo result, int errorCode, String errorMsg) {
                hideLoadingDialog();
                if (isOK && result != null) {
                    LocalUtils.showToast(context, getString(R.string.login_success));
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    LocalUtils.showToast(context,errorMsg);
                }
            }

            @Override
            public void onInternError(int errorCode, final String errorMessage) {
                hideLoadingDialog();
                LocalUtils.showToast(context, errorMessage);
            }
        });
    }

    /**
     * @Description 判断是否为6位验证码
     * @author xiezhidong251@jk.cn
     * @return
     */

    private boolean isVerifyCodeRight() {
        return mPasswordEt.getText().toString().matches("\\d{6}");
    }


    /**
     * @Description 切换键盘
     * @author xiezhidong251@jk.cn
     */

    private void changeInputMethod() {
        mPasswordEt.requestFocus();
    }

}
